/*
 * @Author: your name
 * @Date: 2024-03-28 15:42:57
 * @LastEditTime: 2024-04-03 15:59:07
 * @LastEditors: CaoYanhua
 * @Description: In User Settings Edit
 * @FilePath: \station-b-study\blackHorse学习\vuex学习\vuex_demo01\src\utils\logger.js
 */
import pako from 'pako'
import { saveAs } from 'file-saver' // 用于保存文件
import { Logger } from 'tslog'
class DrpLogger {
  constructor(name,params) {
    
    //创建一个新的Logger实例
    this._logger = new Logger({
      name,
      hideLogPositionForProduction: true, // 优化日志性能
      stylePrettyLogs: true,
      prettyLogTimeZone: "local",//日志输出的时区与本地时区一致  UTC时区和本地差8
    })
    console.log(params,"这是一些公共的参数")
    this.logTotalArr = [] ;//log存储总数据
    this.params = params
    this.lastUploadTime = new Date().getTime()
    this.retryCount = 0; // 请求失败的重试次数
    // 在日志记录时调用发送日志到后台服务器的函数
    this._logger.attachTransport(
      logObj => {
        let cloneObj = JSON.parse(JSON.stringify(logObj))
        console.log("克隆出来的",cloneObj)
        console.log(logObj,"记录的日志对象")
        let formatted = {}
        formatted.userId = this.params.userId
        formatted.browerType = cloneObj._meta.browser
        formatted.deviceType = this.getDeviceType()
        formatted.logLevel = cloneObj._meta.logLevelName
        formatted.time = new Date(cloneObj._meta.date).toLocaleString()
        let selfLogObj = logObj
        for (let key in selfLogObj) {
            if (key.startsWith('_meta')) {  
              delete selfLogObj[key]
              continue;
            } else {
              
            }
        }
        formatted.content = selfLogObj
        // console.log(selfLogObj,"删除掉——meta之后剩下的东西")
        // formatted = Object.assign(formatted,selfLogObj)
        console.log(formatted,"处理之后的格式")
        // console.log(logObj._meta.logLevelName,"日志级别")
        this.logTotalArr.push(formatted)
        console.log(this.logTotalArr,"我打印的所有的日志")
        // this.checkAndUploadLogs()
      },
      // { type: 'custom' }
    )
   
  }
  //获取设备类型
  getDeviceType(){
    const u = navigator.userAgent;
    console.log(u,'ua')
    let isAndroid = u.indexOf("Android") > -1 || u.indexOf("Adr") > -1; //android终端
    let isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
    let isWechat = u.toLowerCase().indexOf("micromessenger")!=-1;//微信浏览器
    if(isiOS) {
      return 'ios'
    }
    if(isAndroid) {
      return "android"
    }
    return 'PC'
  }
  //检查是否达到了日志上传的条件   一定条数or时间
  checkAndUploadLogs(){
    if(this.logTotalArr.length >= 2 || new Date().getTime() - this.lastUploadTime >= 60000){
        //达到20条或者距离上次上传时间超过1分钟
        this.compressIntoGzip(this.logTotalArr)
        //上传完之后清空
        this.logTotalArr = []
        //更新上传时间
        this.lastUploadTime = new Date().getTime()
    }
  }
  //压缩成gzip
  compressIntoGzip(logs){
    console.log(logs,"传过来的88888")
    // console.log(obj,"obj88888")
    // 将日志数据转换为Uint8Array格式
    // const uint8Data = new TextEncoder().encode(JSON.stringify(logs))
    // 使用pako进行gzip压缩
    const compressedData = pako.gzip(JSON.stringify(logs))
    // 创建Blob对象用于保存压缩后的数据
    const blob = new Blob([compressedData], { type: 'application/gzip' })
    //压缩完成  调接口上传给后台
    console.log("哈哈哈  压缩完成啦")
    this.uploadLogToserver(blob)
    // 保存压缩文件
    // saveAs(blob, 'cyhlogs.gzip')
  }
  //调用后台接口上传日志
  uploadLogToserver(blob){
    console.log(blob,"哈哈哈哈该上传接口了")
    let xhr = new XMLHttpRequest();
    xhr.open(
      "POST",
      `https://vcc-dev.ccod.com:17080/logtail/api/v1/upload`,
      true
    );
    xhr.setRequestHeader('Content-Type', 'application/gzip')
    // xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
    // xhr.setRequestHeader("Authorization", "Bearer ");
    xhr.send(blob);
    xhr.onreadystatechange = (e) => {
      if (xhr.readyState == 4 ) {
        if(xhr.status == 200){
          try{
            console.log(JSON.parse(xhr.responseText))
          }catch(ee){
            console.log(ee,"ee")
            console.log(ee,"errrr")
          }
        }else{
          //请求失败
          console.log("request error! Please try once !")
          if (this.retryCount < 1) { // 仅在重试次数小于1时重试
            this.reTryUpload(blob)
          } else {
            console.log("Retry count exceeded. Stop retrying.");
            this.retryCount = 0
          }
        }
        
      }
    };   
  }

  //尝试请求一次
  reTryUpload(blob){
    // 增加重试次数计数
    this.retryCount++;
    // 重试上传日志
    this.uploadLogToserver(blob);
  }


  silly(...args) {
    this._logger.silly(...args)
  }

  trace(...args) {
    this._logger.trace(...args)
  }

  debug(...args) {
    this._logger.debug(...args)
  }

  info(...args) {
    this._logger.info(...args)
  }

  warn(...args) {
    console.log(args,"传进来的参数",typeof args)
    // if(args[0] !== null && typeof args[0] === 'object' && !Array.isArray(args[0])){
    //   console.log("是我要求的类型")
      this._logger.warn(...args)
    // }else{
    //   alert("格式错误，要求为Object类型的")
    // }
  }

  error(...args) {
    this._logger.error(...args)
  }

  fatal(...args) {
    this._logger.fatal(...args)
  }
}

// export const logger = new DrpLogger('sunshine_H5')
export const initLogger = (name, params) => {
  return new DrpLogger(name,params)
}
